'''
Created on Oct 6, 2013

@author: Gabriel
'''
import urllib2
import bs4
import subprocess
import db.databaseMgr
import re
import json
from db.databaseMgr import __loadDatabase
import os

class Search(object):
    '''
    classdocs
    '''
    ENGINE1 = "http://thepiratebay.sx/search/";

    def findFirstSearchResult(self, htmlContent):
        searchResultMagnetLink = {}
        mainSearchDom = bs4.BeautifulSoup(htmlContent)
        searhResultsTable = mainSearchDom.find(id=u'searchResult')
        if searhResultsTable :
            
            # If needed to validate the search results, here is the title of the 1st one
            searchResultTitleTag = searhResultsTable.find(u'a', class_=u'detLink')
            searchResultMagnetLink['name'] = searchResultTitleTag.string
            # print searchResultMagnetLink['name']
            # Get the first magnet link in the search results
            searchResultMagnetLinkTag = searhResultsTable.find(u'a', title=u'Download this torrent using magnet')
            searchResultMagnetLink['link'] = searchResultMagnetLinkTag[u'href']
            # print searchResultMagnetLink
        else :
            # print 'No results matching the search'
            pass
        return searchResultMagnetLink

    def search(self, query):
        url = self.ENGINE1 + urllib2.quote(query.lower())
        # print url
        mainSearchHtml = self.getUrl(url)
        # print mainSearchHtml
        return self.findFirstSearchResult(mainSearchHtml)
        
    def getUrl(self, url):
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; rv:16.0) Gecko/20100101 Firefox/16.0')
        response = urllib2.urlopen(req)
        data = response.read()
        response.close()
        return data
        
        
class TixatiApi(object):

#    COMMAND = '/usr/bin/tixati -starthiddenintray "%s"'
    COMMAND = '"c:\\Program Files\\tixati\\tixati.exe" -starthiddenintray "%s"'
    
    def addDownload(self, magnetLink):
        print self.COMMAND % str(magnetLink.replace('"', ''))
        subprocess.call(self.COMMAND % str(magnetLink).replace('"', ''))


class TorrentDownloadMgr(object):

    DATA = None
    __DB_FILE = 'C:/Users/Gabriel/git/relaxee/relaxeeDbBuilder/torrentDownload.json'

    TEMP_DOWNLOAD_DIR = "C:/tmp/downloads"
    COMPLETED_DOWNLOAD_DIR = "C:/tmp/completed"

    def __init__(self):
        self.__loadDatabase()
        
        
    def __loadDatabase(self):
        try :
            with open(self.__DB_FILE, mode='r') as f :
                rawData = f.read();
                self.DATA = json.loads(rawData)
        except :
            pass
        if not self.DATA :
            self.DATA = {'downloads':[]}
        print self.DATA


    def __saveDatabase(self):
        with open(self.__DB_FILE, mode='w') as dbFile :
            serialized = json.dumps(self.DATA, sort_keys=True, indent=4, separators=(',', ': '))
            dbFile.write(serialized)
    

    def finalizeCompletedDownloads(self):
        entries = os.listdir(self.TEMP_DOWNLOAD_DIR)
        for entry in entries :
            if self.findDownloadByLink(entry) :
                print "Found completed download: " + entry
                
        # List the files and folders of the completed downloads folder
        # If the file is in the tracked files, move it to destination folder
        pass

    def findDownloadByName(self, showName):
        for download in self.DATA['downloads'] :
            if download['name'] == showName :
                return download


    def findDownloadByLink(self, link):
        for download in self.DATA['downloads'] :
            if download['torrent'] == link:
                return download


    def trackDownload(self, showName, magnetLink):
        alreadyTracking = False
        for download in self.DATA['downloads'] :
            if download['name'] == showName :
                alreadyTracking = True
        
        if not alreadyTracking :
            print "Adding download for: " + showName
            # Persist the torrent and the serie name, so it can move it to destination when complete
            #torrentApi = TixatiApi()
            #torrentApi.addDownload(magnetLink['link'])
            self.DATA['downloads'].append({"name":showName, "torrent":magnetLink["name"]})
            self.__saveDatabase()
            
        else :
            print "Serie already being downloaded: " + showName


    def searchNewEpisodes(self):
        search = Search()
        tvShows = db.databaseMgr.DATA['shows']
        # For each series
        for show in tvShows : 
            magnetLink = {}
            showName = show['name']
            # Find the last episode present
            lastEpisode = self._getNextEpisode(show, False)
            if lastEpisode :
                magnetLink = search.search(showName + ' ' + lastEpisode)
                if 'link' not in magnetLink :
                    lastEpisode = self._getNextEpisode(show, True)
                    if lastEpisode :
                        magnetLink = search.search(showName + ' ' + lastEpisode)
            if 'link' in magnetLink :
                self.trackDownload(showName, magnetLink)


    def _getNextEpisode(self, show, increaseSeason):
        lastEpisode = len(show['episodes']) - 1
        path = show['episodes'][lastEpisode]
        
        match = re.compile('S(\d{1,4})E(\d{1,2})', re.I).findall(path)
        if len(match) > 0 :
            if increaseSeason :
                return 'S%02dE%02d' % (int(match[0][0]) + 1, 1)
            else :
                return 'S%02dE%02d' % (int(match[0][0]), int(match[0][1]) + 1)
        else :
            return None

    
if __name__ == '__main__':
    downloadMgr = TorrentDownloadMgr()
    #downloadMgr.searchNewEpisodes()
    downloadMgr.finalizeCompletedDownloads()
#    magnetLink = search.search("south park s17e01")
#    print magnetLink
#    
#    tixatiApi = TixatiApi()
#    tixatiApi.addDownload(magnetLink)



#   Search for the next episode by incrementing episode number
#   If nothing found, search by incrementing season and resetting episode number
#   If nothing found, give up
#   If found, download it
